package com.woniuxy.ticketfile.controller;

import com.woniuxy.commnes.entity.ResponseResult;
import com.woniuxy.ticketfile.util.OssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.UUID;

@RestController
@RequestMapping("file")
public class FIleTanController {
    @Value("${file.location}")
    private String fileLocation;

    /**
     * 返回文件名
     * @param file
     * @return
     */
    @PostMapping("upload")
    public ResponseResult<String> upload(MultipartFile file) {
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        File file1 = new File(fileLocation);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        File newFile = new File(file1, fileName + suffix);
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseResult<>(fileName + suffix);

    }

    @Autowired
    private OssUtil ossUtil;

    /**
     *返回绝对路径
     * @param file
     * @return
     */
    @PostMapping("upload2oss")
    public ResponseResult<String> upload2oss(MultipartFile file) {
        String url = ossUtil.uploadFile(file);
        SimpleDateFormat date = new SimpleDateFormat("yyyy.MM.dd ");
        return new ResponseResult<>(200,date+"",url);
    }
}
